package com.weishaoying.rws.aspect;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WeiShaoying
 * @date 2018/5/5
 */
public class ChooseDataSource extends AbstractRoutingDataSource {

    //key=read, value=get,select,count,list,query
    //key=write, value=add,save,create,update,delete,remove
    static Map<String, List<String>> METHOD_TYPE_MAP = new HashMap<>();

    //Spring容器启动创建这个bean时，就会调用这个方法，为属性赋值
    public void setMethodType(Map<String, String> map) {
        for (String key : map.keySet()) {
            List<String> list = new ArrayList<>();
            String[] methods = map.get(key).split(",");

            for (String type : methods) {
                if (StringUtils.isNotBlank(type)) {
                    list.add(type);
                }
            }
            System.out.println("========ChooseDataSource.key = " + key);
            System.out.println("========ChooseDataSource.list = " + list);
            METHOD_TYPE_MAP.put(key, list);
        }
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSource();
    }
}
